package com.chengxiaoxiao.libarypartner.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;

import com.chengxiaoxiao.libarypartner.R;
import com.chengxiaoxiao.libarypartner.constants.AppConsrants;
import com.chengxiaoxiao.libarypartner.constants.Consrants;
import com.chengxiaoxiao.libarypartner.utils.ApiAddress;
import com.chengxiaoxiao.libarypartner.utils.LoadDialogUtils;
import com.chengxiaoxiao.libarypartner.utils.LoginUtils;
import com.chengxiaoxiao.libarypartner.utils.SPUtils;
import com.chengxiaoxiao.libarypartner.utils.ToastUtils;
import com.chengxiaoxiao.libarypartner.utils.UserUtils;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.zxing.activity.CaptureActivity;

import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

public class BorrowActivity extends Activity
{
    String ids;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_borrow);


        ToastUtils.makeText(BorrowActivity.this, "请扫描管理员端，借书二维码完成验证");
        Intent scanIntent = getIntent();
        ids = scanIntent.getStringExtra(AppConsrants.SCAN_BORROW_IDS);

        if(!LoginUtils.getLoginStatus(BorrowActivity.this))
        {
            ToastUtils.makeText(BorrowActivity.this,"您还没有登录，登陆后进行操作");
            startActivity(new Intent(BorrowActivity.this,LoginActivity.class));
        }


        //验证二维码
        Intent intent = new Intent(BorrowActivity.this, CaptureActivity.class);
        startActivityForResult(intent, 0);

    }

    /**
     * 接收二维码的结果
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK)
        {
            /**
             * 获取扫描的条形码
             */
            String msg = data.getExtras().getString("result");

            //判断扫描的是二维码还是条形码
            if (msg.contains("{"))
            {
                try
                {
                    JSONObject json = new JSONObject(msg);

                    String op = json.getString("op");
                    String date = json.getString("date");
                    String adminId = json.getString("adminId");

                    //ToastUtils.makeText(BorrowActivity.this,"op:"+op+" date:"+date+" adminId:"+adminId);

                    if ("borrow".equalsIgnoreCase(op))
                    {
                        borrow();
                    } else if ("return".equalsIgnoreCase(op))
                    {
                        returns();
                    }


                } catch (Exception e)
                {

                }


            } else
            {

                ToastUtils.makeText(BorrowActivity.this, "请扫描管理员端，借书二维码完成验证");
            }
        }
    }

    /**
     * 还书
     */
    private void returns()
    {
        ToastUtils.makeText(BorrowActivity.this,"请扫描还书二维码");
    }

    /**
     * 借书
     */
    private void borrow()
    {
        LoadDialogUtils.show(BorrowActivity.this,"","借书中，请稍候...");
        if (ids.contains(","))
        {
            String[] idArray = ids.split(",");

            for (int i = 0; i < idArray.length; i++)
            {
                if (idArray[i].equalsIgnoreCase(""))
                {
                    continue;
                }

                borrowBook(idArray[i]);
            }
        } else
        {
            borrowBook(ids);
        }

        LoadDialogUtils.hidden();

    }

    /**
     * 借书逻辑
     * @param bookId
     */
    private void borrowBook(final String bookId)
    {
        if (!LoginUtils.getLoginStatus(BorrowActivity.this))
        {
            startActivity(new Intent(BorrowActivity.this, LoginActivity.class));
            return;
        }

        String userName = UserUtils.getNumber(BorrowActivity.this);

        AsyncHttpClient client = new AsyncHttpClient();

        RequestParams params = new RequestParams();
        params.add("userId", userName);
        params.add("bookId", bookId);

        client.post(ApiAddress.getApiDomain() + "/client/ClientServlet?op=borrow", params, new AsyncHttpResponseHandler()
        {
            @Override
            public void onSuccess(int statusCode, org.apache.http.Header[] headers, byte[] responseBody)
            {

                String body = new String(responseBody);

                try
                {
                    JSONObject jsonObj = new JSONObject(body);
                    String status = jsonObj.getString(Consrants.JSON_RESPONSE_KEY_STATUS);
                    String msg = jsonObj.getString(Consrants.JSON_RESPONSE_KEY_ERRORMSG);



                    if("ok".equalsIgnoreCase(status))
                    {
                        ToastUtils.makeText(BorrowActivity.this,"借阅成功");
                        if(ids.contains(","))
                        {
                            int index =ids.indexOf(bookId);

                            SPUtils.putString(AppConsrants.BORROW_LIST_ID, "", BorrowActivity.this);

                            startActivity(new Intent(BorrowActivity.this,MainActivity.class));
                        }
                        else
                        {
                            startActivity(new Intent(BorrowActivity.this,MainActivity.class));
                        }

                    }
                    else
                    {
                        ToastUtils.makeText(BorrowActivity.this, msg);
                    }

                } catch (JSONException e)
                {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error)
            {
                LoadDialogUtils.hidden();
                ToastUtils.makeText(getApplication(), "网络连接错误");
            }
        });


    }
}
